package com.artmofang.controller;

import com.artmofang.bo.ErpStudentBO;
import com.artmofang.bo.ErpStudentUpdateBO;
import com.artmofang.common.utils.JSONResult;
import com.artmofang.pojo.ArtOaCourse;
import com.artmofang.pojo.ArtOaSchoolClass;
import com.artmofang.service.EprStudentService;
import com.artmofang.vo.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.artmofang.vo.ErpClassJoinStudentAndUsersVO;

@Api(value = "学生相关", tags = {"学生相关接口"})
@RestController
@RequestMapping("erp_student")
public class ErpStudentController {

    @Autowired
    private EprStudentService eprStudentService;

    @ApiOperation(value = "新增学生", notes = "新增学生", httpMethod = "POST")
    @PostMapping("/add")
    public Object add(@RequestBody @Valid ErpStudentBO erpStudentBO, BindingResult validResult) {

        //判断是否保存错误验证信息，有则直接RETURN
        if (validResult.hasErrors()) {
            Map<String, String> errorMap = getErrors(validResult);
            return JSONResult.errorMap(errorMap);
        }

        int result = eprStudentService.add(erpStudentBO);
        if (result == 0) {
            return JSONResult.errorMsg("学生新增失败");
        }
        return JSONResult.ok();
    }

    @ApiOperation(value = "查询意向课程列表", notes = "查询意向课程列表", httpMethod = "GET")
    @GetMapping("/queryCourse")
    public Object queryCourse(Integer oesid) {

        List<ArtOaCourse> list = eprStudentService.queryCourse(oesid);
        return JSONResult.ok(list);
    }

    @ApiOperation(value = "查询机构学生", notes = "查询机构学生", httpMethod = "GET")
    @GetMapping("/searchStudent")
    public Object searchStudent(Integer oesid, String os_phone, String os_name) {

        Map<String, Object> map = new HashMap<>();
        map.put("oesid", oesid);
        map.put("os_phone", os_phone);
        map.put("os_name", os_name);
        List<ErpStudentJoinClassVO> list = eprStudentService.queryErpStudents(map);

        for (ErpStudentJoinClassVO erpStudentJoinClassVO : list) {


            //获取年龄
            Long age = getAgeByBirth(erpStudentJoinClassVO.getOs_birthday());
            erpStudentJoinClassVO.setOs_birthday(Math.toIntExact(age));

            String className = "";

            Integer surplusClassCounts = 0;

            Integer surplusClassCountMonthDays = 0;

            Integer course_id = 0;

            for (StudentClassNameAndSurplusClassVO item : erpStudentJoinClassVO.getOtherInfo()) {

                className += item.getOsc_name() + "/";

                if (item.getOscr_surplus_class() == null) {
                    continue;
                }

                //判断课时是否一样
                if (course_id == 0 || !course_id.equals(item.getOsc_course_id())) {

                    //包月类型
                    if (item.getOscr_surplus_class().indexOf(",") != -1) {

                        String[] s = item.getOscr_surplus_class().split(",");

                        Integer r = (Integer.parseInt(s[0]) * 30) + Integer.parseInt(s[1]);

                        surplusClassCountMonthDays += r;

                        course_id = item.getOsc_course_id();

                        //课时类型
                    } else {

                        surplusClassCounts += Integer.parseInt(item.getOscr_surplus_class());

                        course_id = item.getOsc_course_id();

                    }

                }

            }


            if (className.equals("") && className.length() == 0) {
                className = "无";
            } else {
                className = className.substring(0, className.length() - 1);
            }


            String resultSurpluer = "";
            if (surplusClassCountMonthDays != 0) {
                Integer month = surplusClassCountMonthDays / 30;
                Integer day = surplusClassCountMonthDays % 30;
                resultSurpluer = month + "," + day;
            }

            if (surplusClassCounts != 0) {
                resultSurpluer = surplusClassCounts + "";
            }

            erpStudentJoinClassVO.setResultClassName(className);
            erpStudentJoinClassVO.setResultSurpluerClass(resultSurpluer);
            erpStudentJoinClassVO.setOtherInfo(null);
        }

        return JSONResult.ok(list);
    }

    @ApiOperation(value = "更新学员信息", notes = "更新学员信息", httpMethod = "POST")
    @PostMapping("/updateStudent")
    public Object updateStudent(Integer studentId, @RequestBody ErpStudentUpdateBO erpStudentUpdateBO) {
        int result = eprStudentService.update(studentId, erpStudentUpdateBO);
        if (result == 0) {
            return JSONResult.errorMsg("更新失败");
        }
        return JSONResult.ok();
    }

    private Map<String, String> getErrors(BindingResult result) {

        Map<String, String> map = new HashMap<>();
        List<FieldError> errorList = result.getFieldErrors();
        for (FieldError error : errorList) {
            String errorField = error.getField();
            String errorMsg = error.getDefaultMessage();
            map.put(errorField, errorMsg);
        }
        return map;
    }

    private Long getAgeByBirth(Integer b) {
        Long endTime = System.currentTimeMillis() / 1000;
        Long ageTime = endTime - b;
        return ageTime / 60 / 60 / 24 / 365;
    }

    @ApiOperation(value = "查询学生详情", notes = "查询学生详情", httpMethod = "GET")
    @GetMapping("/querySingleStudent")
    public Object querySingleStudent(Integer studentId) {
        Map<String, Object> map = new HashMap<>();
        map.put("studentId", studentId);
        List<ErpStudentJoinCourseVO> result = eprStudentService.queryStudentJoinCourse(map);
        return JSONResult.ok(result);
    }

    @ApiOperation(value = "查询班级学生", notes = "查询班级学生", httpMethod = "GET")
    @GetMapping("/classStudent")
    public Object queryStudentByClassId(Integer oesid, String className) {
        Map<String, Object> map = new HashMap<>();
        map.put("oesid", oesid);
        map.put("className", className);
        List<ErpClassJoinStudentAndUsersVO> result = eprStudentService.queryStudentByClassId(map);
        for (ErpClassJoinStudentAndUsersVO item : result) {
            Long age = getAgeByBirth(item.getOs_birthday());
            item.setOs_birthday(Math.toIntExact(age));
        }

        return JSONResult.ok(result);
    }

    @ApiOperation(value = "学生信息下载数据", notes = "学生信息下载数据", httpMethod = "GET")
    @GetMapping("/queryDownloadStudent")
    public Object queryDownloadStudent(Integer oesid, Integer osc_id, Integer osc_start_time, Integer osc_end_time) {
        Map<String, Object> map = new HashMap<>();
        map.put("oesid", oesid);
        map.put("osc_id", osc_id);
        map.put("osc_start_time", osc_start_time);
        map.put("osc_end_time", osc_end_time);
        List<ErpStudentDownloadVo> result = eprStudentService.queryStudentDownloadList(map);
        for (ErpStudentDownloadVo erpStudentDownloadVo : result) {
            //获取年龄
            Long age = getAgeByBirth(erpStudentDownloadVo.getOs_birthday());
            erpStudentDownloadVo.setOs_birthday(Math.toIntExact(age));
        }

        return JSONResult.ok(result);
    }

    @ApiOperation(value = "班级列表", notes = "班级列表", httpMethod = "GET")
    @GetMapping("/queryClass")
    public Object queryClass(Integer oesid) {

        List<ArtOaSchoolClass> list = eprStudentService.queryClass(oesid);
        return JSONResult.ok(list);
    }
}
